<?php
/**
 *  
 * @package admin
 * @author Mervin.Wong<mervin0502@163.com>
 * @Copyright
 * @license  http://www.apache.org/licenses/LICENSE-2.0
 * @version 0.1.0
 * @date 2013-2-23上午10:43:25
 *
 */
 
  /**
 * CanGoo category 控制器
 *
 *	分类管理模块
 *
 * @package		admin
 * @subpackage	Controllers
 * @category	Admin-controllers
 * @author		Mervin.Wong<mervin0502@163.com
 * @link		http://mervin.me/project/cangoo
 */ 
 
 class Category extends CI_Controller{
 	
 	/**
 	 * 构造函数
 	 */
 	public function __construct(){
 		parent::__construct();
 		//模型类
 		$this->load->model('category_model');
 		
 		$this->load->helper('date');
 		$this->load->helper('url');
 		$this->load->helper('common');
 		
 		$this->load->library('session');
 		$this->load->model('common_model');
 		if(!$this->common_model->is_login($this->session->userdata('session_id'))){
 			redirect(site_url('index/login', 'refresh'));
 		}
 		$this->load->helper('form');
 		
		
 		//表单检测
 		$this->load->library('form_validation');
 		/* 验证规则 */
 		$this->form_validation->set_rules('cat_name', '分类名', 'trim|required|min_length[2]|max_length[12]|callback_check[name]|xss_clean');//分类名
 		$this->form_validation->set_rules('cat_slug', '分类别名', 'trim|required|min_length[2]|max_length[12]|alpha_dash|callback_check[slug]|xss_clean');//分类别名
 		$this->form_validation->set_rules('cat_description', '分类描述', 'trim|required|xss_clean|prep_for_form');//分类描述
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[passconf]|md5');
		//$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required');
		//$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
		
		
 	}
 	
 	/**
 	 * 默认方法
 	 * @access public
 	 * @param string $action 执行的动作CURD
 	 * @param int $tid 分类的ID，更新 删除时需要
 	 * @return void
 	 */
 	public function index($action = '', $tid = 0){
 		/* 获取所有的类 */
 		$tree = $this->category_model->get_category_tree(array('tid', 'parent', 'name')); 
 		$cat_list = array(0=>'无父类');
 		foreach($tree as $k=>$v){
 			$cat_list[$k]=$v['parent_category']['name'];
			/*if(isset($v['sub_category'])){
	 			foreach($v['sub_category'] as $k2=>$v2){
	 				 一个子类属于一个父类 
	 				$cat_list[$k2] = '--'.$v2['name'];
	 			}
 			}*/
 		}
 		
 		
 		$data['cat_table'] = $this->_table();
 		
 		
 		if(!isset($action) || empty($action)){
 			//默认表单 
	 		/* 右侧的表单 */
	 		$cat_form = form_open('category/index/add', array('class'=>'cat_form','id'=>'cat_form'));
	 		$cat_form .= form_fieldset('添加分类');
	 		$cat_form .= '<p>';
	 		$cat_form .= form_label('分类名:','cat_name');
	 		$cat_form .= form_input(array('name'=>'cat_name', 'id'=>'cat_name', 'value' => set_value('cat_name'), 'size'=>12));
	 		$cat_form .= '</p><p>';
	 		$cat_form .= form_label('分类别名:', 'cat_slug');
	 		$cat_form .= form_input(array('name'=>'cat_slug', 'id'=>'cat_slug', 'value'=>set_value('cat_slug'), 'size'=>12));
	 		$cat_form .= '</p><p>';
	 		$cat_form .= form_label('所属父类:', 'cat_parent');
	 		$cat_form .= form_dropdown('cat_parent', $cat_list);
	 		$cat_form .= '</p><p>';
	 		$cat_form .= form_label('分类描述:', 'cat_description', 'id="description"');
	 		$cat_form .= form_textarea(array('name'=>'cat_description', 'id'=>'cat_description', 'rows'=>4, 'cols'=>20, 'value'=>set_value('cat_description')));
	 		$cat_form .= '</p><p>';
	 		$cat_form .= form_label('设为默认分类', 'cat_isDefault');
	 		$cat_form .= form_checkbox(array('name'=>'cat_isDefault', 'id'=>'cat_isDefault', 'value'=>'default_cat', set_checkbox('cat_isDefault','default_cat')));
	 		$cat_form .= '</p><p>';
	 		$cat_form .= form_hidden('cat_id',$tid);//分类的ID
	 		$cat_form .= form_hidden('is_submit', 'submit');//判断是否提交
	 		$cat_form .= form_reset('cat_reset', '重写');
	 		$cat_form .= form_submit('cat_submit', '提交');
	 		$cat_form .= form_fieldset_close();
	 		$cat_form .= form_close();
	 		$data['cat_form'] = $cat_form;
	 		$this->load->view('category_view.php', $data);
 			
 		} else if($action == 'add'){
 			//添加一个分类 表单
 			if($this->form_validation->run() == TRUE){
 				//插入数据库
 				$this->_insert();
 				redirect(site_url('category/index'));
 			}else{
 				/* 右侧的表单 */
		 		$cat_form = form_open('category/index/add', array('class'=>'cat_form','id'=>'cat_form'));
		 		$cat_form .= form_fieldset('添加分类');
		 		$cat_form .= '<p>';
		 		$cat_form .= form_label('分类名:','cat_name');
		 		$cat_form .= form_input(array('name'=>'cat_name', 'id'=>'cat_name', 'value' => set_value('cat_name'), 'size'=>12));
		 		$cat_form .= '</p><p>';
		 		$cat_form .= form_label('分类别名:', 'cat_slug');
		 		$cat_form .= form_input(array('name'=>'cat_slug', 'id'=>'cat_slug', 'value'=>set_value('cat_slug'), 'size'=>12));
		 		$cat_form .= '</p><p>';
		 		$cat_form .= form_label('所属父类:', 'cat_parent');
		 		$cat_form .= form_dropdown('cat_parent', $cat_list, $this->input->post('cat_parent'));
		 		$cat_form .= '</p><p>';
		 		$cat_form .= form_label('分类描述:', 'cat_description', 'id="description"');
		 		$cat_form .= form_textarea(array('name'=>'cat_description', 'id'=>'cat_description', 'rows'=>4, 'cols'=>20, 'value'=>set_value('cat_description')));
		 		$cat_form .= '</p><p>';
		 		$cat_form .= form_label('设为默认分类', 'cat_isDefault');
		 		$cat_form .= form_checkbox(array('name'=>'cat_isDefault', 'id'=>'cat_isDefault', 'value'=>'default_cat', set_checkbox('cat_isDefault','default_cat')));
		 		$cat_form .= '</p><p>';
		 		$cat_form .= form_hidden('cat_id',$tid);//分类的ID
		 		$cat_form .= form_hidden('is_submit', 'submit');//判断是否提交
		 		$cat_form .= form_reset('cat_reset', '重写');
		 		$cat_form .= form_submit('cat_submit', '提交');
		 		$cat_form .= form_fieldset_close();
		 		$cat_form .= form_close();
		 		$data['cat_form'] = $cat_form;
		 		$this->load->view('category_view.php', $data);
 			}
 			
 		} else if($action == 'edit'){
 			//更新一个分类 表单
 			if($this->input->post('is_submit') != 'submit'){
 				//提交之前
 				$row = $this->category_model->get_one(array('name', 'slug', 'parent', 'description', 'isDefault'), $tid);
 				/* 右侧的表单 */
		 		$cat_form = form_open('category/index/edit/'.$tid, array('class'=>'cat_form','id'=>'cat_form'));
		 		$cat_form .= form_fieldset('编辑分类');
		 		$cat_form .= '<p>';
		 		$cat_form .= form_label('分类名:','cat_name');
		 		$cat_form .= form_input(array('name'=>'cat_name', 'id'=>'cat_name', 'value' => $row['name'], 'size'=>12));
		 		$cat_form .= '</p><p>';
		 		$cat_form .= form_label('分类别名:', 'cat_slug');
		 		$cat_form .= form_input(array('name'=>'cat_slug', 'id'=>'cat_slug', 'value'=> $row['slug'], 'size'=>12));
		 		$cat_form .= '</p><p>';
		 		$cat_form .= form_label('所属父类:', 'cat_parent');
		 		$cat_form .= form_dropdown('cat_parent', $cat_list, $row['parent']);
		 		$cat_form .= '</p><p>';
		 		$cat_form .= form_label('分类描述:', 'cat_description', 'id="description"');
		 		$cat_form .= form_textarea(array('name'=>'cat_description', 'id'=>'cat_description', 'rows'=>4, 'cols'=>20, 'value'=>$row['description']));
		 		$cat_form .= '</p><p>';
		 		$cat_form .= form_label('设为默认分类', 'cat_isDefault');
		 		$cat_form .= form_checkbox(array('name'=>'cat_isDefault', 'id'=>'cat_isDefault', 'value'=>'default_cat', 'checked'=>($row['isDefault'] == 1)?TRUE:FALSE));
		 		$cat_form .= '</p><p>';
		 		$cat_form .= form_hidden('cat_id',$tid);//分类的ID
		 		$cat_form .= form_hidden('is_submit', 'submit');//判断是否提交
		 		$cat_form .= form_reset('cat_reset', '重写');
		 		$cat_form .= form_submit('cat_submit', '提交');
		 		$cat_form .= form_fieldset_close();
		 		$cat_form .= form_close();
		 		$data['cat_form'] = $cat_form;
		 		$this->load->view('category_view.php', $data);
 			}else{
 				
 				if($this->form_validation->run() == TRUE){
 					//提交之后，检测通过,跟新数据
 					$this->_update($tid);
 					redirect(site_url('category/index'));
 				}else{
 					//提交之后，检测失败
	 				/* 右侧的表单 */
			 		$cat_form = form_open('category/index/edit/'.$tid, array('class'=>'cat_form','id'=>'cat_form'));
			 		$cat_form .= form_fieldset('编辑分类');
			 		$cat_form .= '<p>';
			 		$cat_form .= form_label('分类名:','cat_name');
			 		$cat_form .= form_input(array('name'=>'cat_name', 'id'=>'cat_name', 'value' => set_value('cat_name'), 'size'=>12));
			 		$cat_form .= '</p><p>';
			 		$cat_form .= form_label('分类别名:', 'cat_slug');
			 		$cat_form .= form_input(array('name'=>'cat_slug', 'id'=>'cat_slug', 'value'=>set_value('cat_slug'), 'size'=>12));
			 		$cat_form .= '</p><p>';
			 		$cat_form .= form_label('所属父类:', 'cat_parent');
			 		$cat_form .= form_dropdown('cat_parent', $cat_list, $this->input->post('cat_parent'));
			 		$cat_form .= '</p><p>';
			 		$cat_form .= form_label('分类描述:', 'cat_description', 'id="description"');
			 		$cat_form .= form_textarea(array('name'=>'cat_description', 'id'=>'cat_description', 'rows'=>4, 'cols'=>20, 'value'=>set_value('cat_description')));
			 		$cat_form .= '</p><p>';
			 		$cat_form .= form_label('设为默认分类', 'cat_isDefault');
			 		$cat_form .= form_checkbox(array('name'=>'cat_isDefault', 'id'=>'cat_isDefault', 'value'=>'default_cat', set_checkbox('cat_isDefault','default_cat')));
			 		$cat_form .= '</p><p>';
			 		$cat_form .= form_hidden('cat_id',$tid);//分类的ID
			 		$cat_form .= form_hidden('is_submit', 'submit');//判断是否提交
			 		$cat_form .= form_reset('cat_reset', '重写');
			 		$cat_form .= form_submit('cat_submit', '提交');
			 		$cat_form .= form_fieldset_close();
			 		$cat_form .= form_close();
			 		$data['cat_form'] = $cat_form;
			 		$this->load->view('category_view.php', $data); 					
 				}
 			}
 			
 			
 		} else if($action == 'del'){
 			//删除一个分类
 			$this->_delete($tid);
 			redirect(site_url('category/index'));
 		} else if($action == 'default_cat'){
 			//设为默认分类
 			$this->_set_default_cat($tid);
 			redirect(site_url('category/index'));
 		}
 	}
 	
 	/**
 	 * 分类列表
 	 * @access public
 	 * @param int $page 翻页
 	 * @return void
 	 */
 	public function listing($page = 1){
 		$total = $this->category_model->get_num('tid', 'taxonomy', array('type'=>'category'));
 		$per = 3;
 		$data['pagination'] = pagination_set(site_url('category/listing'), $total, $per, 3);
 		$data['cat_table'] = $this->_table($page, $per);
 		
 		$action = site_url('category/add');
		$values['head']= '添加分类';
		$values['name']= '';
		$values['slug']= '';
		$values['cat_list']= $this->_cat_list();
		$values['cat_selected']= '';
		$values['module_list']= $this->config->item('module');
		$values['module_selected']= '';
		$values['description']= '';
 		$values['cat_isDefault'] = '';
 		$values['tid'] = 0;
 		$this->_form($action, $values);
 	}
 	
 	
 	
 	/**
 	 * 向数据库添加一个分类
 	 * @access private
 	 */
 	private function _insert(){
 		$args['name'] = $this->input->post('cat_name');
 		$args['slug'] = $this->input->post('cat_slug');
 		$args['parent'] = $this->input->post('cat_parent');
 		$args['description'] = $this->input->post('cat_description');
 		$args['isDefault'] = ($this->input->post('cat_isDefault') == 'default_cat')?1:0;
 		
 		$args['module'] = 'blog';
 		$args['type'] = 'category';
 		$args['count'] = 0;
 		$args['addTime'] = now();
 		$args['modTime'] = now();
		$this->category_model->insert($args); 		
 	}
 	/**
 	 * 编辑分类
 	 * @access private
 	 * @param int $tid 分类ID
 	 */
 	private function _update($tid){
 		$args['name'] = $this->input->post('cat_name');
 		$args['slug'] = $this->input->post('cat_slug');
 		$args['parent'] = $this->input->post('cat_parent');
 		$args['description'] = $this->input->post('cat_description');
 		$args['isDefault'] = ($this->input->post('cat_isDefault') == 'default_cat')?1:0;
 		
 		$args['module'] = 'blog';
 		$args['type'] = 'category';
 		$args['modTime'] = now();
		$this->category_model->update($tid, $args); 	
 	}
 	
 	/**
 	 * 删除分类
 	 * @access private
 	 * @param int $tid 分类ID
 	 */
 	private function _delete($tid){
 		$this->category_model->delete($tid);
 	}
 	
 	/**
 	 * 设为默认分类
 	 * @access private
 	 */
 	 private function _set_default_cat($tid){
 	 	$this->category_model->set_default_cat($tid);
 	 }
 	
 	private function _form($action, $values){
 		/* 右侧的表单 */
 		$cat_form = form_open($action, array('class'=>'cat_form','id'=>'cat_form'));
 		$cat_form .= form_fieldset($values['caption']);
 		$cat_form .= '<p>';
 		$cat_form .= form_label('分类名:','cat_name');
 		$cat_form .= form_input(array('name'=>'cat_name', 'id'=>'cat_name', 'value' => $values['name'], 'size'=>12));
 		$cat_form .= '</p><p>';
 		$cat_form .= form_label('分类别名:', 'cat_slug');
 		$cat_form .= form_input(array('name'=>'cat_slug', 'id'=>'cat_slug', 'value'=>$values['slug'], 'size'=>12));
 		$cat_form .= '</p><p>';
 		$cat_form .= form_label('所属父类:', 'cat_parent');
 		$cat_form .= form_dropdown('cat_parent', $values['cat_list'], $values['cat_selected']);
 		$cat_form .= '</p><p>';
 		$cat_form .= form_label('所属模块:', 'cat_module');
 		$cat_form .= form_dropdown('cat_module', $values['module_list'], $values['module_selected']);
 		$cat_form .= '</p><p>';
 		$cat_form .= form_label('分类描述:', 'cat_description', 'id="description"');
 		$cat_form .= form_textarea(array('name'=>'cat_description', 'id'=>'cat_description', 'rows'=>4, 'cols'=>20, 'value'=>$values['description']));
 		$cat_form .= '</p><p>';
 		$cat_form .= form_label('设为默认分类', 'cat_isDefault');
 		$cat_form .= form_checkbox(array('name'=>'cat_isDefault', 'id'=>'cat_isDefault', 'value'=>'default_cat', $values['cat_isDefault']));
 		$cat_form .= '</p><p>';
 		$cat_form .= form_hidden('cat_id',$values['tid']);//分类的ID
 		$cat_form .= form_hidden('is_submit', 'ok');//判断是否提交
 		$cat_form .= form_reset('cat_reset', '重写');
 		$cat_form .= form_submit('cat_submit', '提交');
 		$cat_form .= form_fieldset_close();
 		$cat_form .= form_close();		
 		
 	}
 	/**
 	 * 分类列表
 	 * @access private
 	 */
 	private function _table($page, $per){
 		//表格类
 		$this->load->library('table');
 		$tmpl = array (
                    'table_open'          => '<table id="cat_table" border="0" cellpadding="4" cellspacing="0">',

                    'heading_row_start'   => '<tr>',
                    'heading_row_end'     => '</tr>',
                    'heading_cell_start'  => '<th>',
                    'heading_cell_end'    => '</th>',

                    'row_start'           => '<tr class="t1">',
                    'row_end'             => '</tr>',
                    'cell_start'          => '<td>',
                    'cell_end'            => '</td>',

                    'row_alt_start'       => '<tr class="t2">',
                    'row_alt_end'         => '</tr>',
                    'cell_alt_start'      => '<td>',
                    'cell_alt_end'        => '</td>',

                    'table_close'         => '</table>'
              );
		$this->table->set_template($tmpl);
		$this->table->set_heading('分类名', '分类别名', '所属父类', '文章数','操作');
 		/* 获取所有的分类的详细信息 */
 		$offset = ($page-1)*$per;
 		$tree = $this->category_model->get_category_tree(array('tid', 'parent', 'slug', 'name', 'description', 'count', 'isDefault'), array('type'=>'category'), $offset, $per); 
 		$cat_list = array();
 		foreach($tree as $k=>$v){
 			if(isset($v['parent_category'])){
	 			$cat_list[$k]['name']=$v['parent_category']['name'];
	 			$cat_list[$k]['slug']=$v['parent_category']['slug'];
	 			$cat_list[$k]['parent']="无父类";
	 			//$cat_list[$k]['description'] = $v['parent_category']['description'];
	 			$cat_list[$k]['count'] = $v['parent_category']['count'];
	 			$cat_list[$k]['operation'] =  anchor(site_url('category/index/edit/'.$v['parent_category']['tid']),'编辑');
	 			$cat_list[$k]['operation'].= '&nbsp;'.anchor(site_url('category/index/del/'.$v['parent_category']['tid']),'删除');;
	 			$cat_list[$k]['operation'].= ($v['parent_category']['isDefault'] == 1)?"":'&nbsp;'.anchor(site_url('category/index/default_cat/'.$v['parent_category']['tid']),'设为默认分类');
	 			//$this->table->add_row(array('class'=>"parent"), $cat_list[$k]);
 			}
			if(isset($v['sub_category'])){
		 			foreach($v['sub_category'] as $k2=>$v2){
		 				// 一个子类属于一个父类 
		 				$cat_list[$k2]['name'] = '--'.$v2['name'];
		 				$cat_list[$k2]['slug']=$v2['slug'];
			 			$cat_list[$k2]['parent']= $cat_list[$v2['parent']]['name'];
			 			//$cat_list[$k2]['description'] = $v2['description'];
			 			$cat_list[$k2]['count'] = $v2['count'];
			 			$cat_list[$k2]['operation'] = anchor(site_url('category/index/edit/'.$v2['tid']),'编辑');
			 			$cat_list[$k2]['operation'].= '&nbsp;'.anchor(site_url('category/index/del/'.$v2['tid']),'删除');
			 			$cat_list[$k2]['operation'].=($v2['isDefault'] == 1)?"":'&nbsp;'.anchor(site_url('category/index/default_cat/'.$v2['tid']),'设为默认分类');
			 			//$this->table->add_row(array('class'=>"children"), $cat_list[$k2]);
		 			}
	 			}
 		}
		
		return  $this->table->generate($cat_list);
		//return  $this->table->generate();
 	}
 	
 	private function _cat_list(){
 		/* 获取所有的类 */
 		$tree = $this->category_model->get_category_tree(array('tid', 'parent', 'name')); 
 		$cat_list = array(0=>'无父类');
 		foreach($tree as $k=>$v){
 			$cat_list[$k]=$v['parent_category']['name'];
			/*if(isset($v['sub_category'])){
	 			foreach($v['sub_category'] as $k2=>$v2){
	 				 一个子类属于一个父类 
	 				$cat_list[$k2] = '--'.$v2['name'];
	 			}
 			}*/
 		}
 		return $cat_list;
 	}
 	
 	/**
 	 * 服务器端重复检测
 	 */
 	 public function check($value, $field){
 	 	
 	 	if($this->category_model->check($value, $field, $this->input->post('cat_id'))){
 	 		//第三个参数表示该分类不是添加动作
 	 		// 存在
 	 		$this->form_validation->set_message('check', '%s:"'.$value.'"已存在！');
 	 		return false;
 	 	}else{
 	 		return true;
 	 	}
 	 }
 }
/* End of file category.php */
/* Loaction : ./apps/admin/controllers/category.php */
